package cn.com.qingz.modules.security.realm;

import org.apache.log4j.Logger;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class LocalAuthorRealm extends AuthorizingRealm {

    private static Logger logger = Logger.getLogger(AuthorizingRealm.class);

    private String defaultRoles = ""; // 默认角色

    private String defaultPurviews = ""; // 默认权限

    /**
     * 重写认证方法
     */
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;

        return new SimpleAuthenticationInfo(token.getUsername(), token.getCredentials(), getName());
    }

    /**
     * 重写授权方法
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //UserSession currentRole = LocalSessionHolder.USER_HOLDER.get(principals.getPrimaryPrincipal().toString());
        //info.addRole(currentRole.getRoleName());

        //		Subject subject = SecurityUtils.getSubject();
        ////		subject.login(shiro_token); //登录
        //		UserSession user = (UserSession) subject.getSession().getAttribute("user");
        //		info.addRole(user.getRoleName());
        return info;
    }

    /**
     * 更新用户授权信息缓存.
     */
    /*
     * protected void clearCachedAuthorizationInfo(PrincipalCollection
     * principal) { SimplePrincipalCollection principals = new
     * SimplePrincipalCollection( principal, getName());
     * clearCachedAuthorizationInfo(principals); }
     */

    /**
     * 清除所有用户授权信息缓存.
     */
    /*
     * public void clearAllCachedAuthorizationInfo() { Cache<Object,
     * AuthorizationInfo> cache = getAuthorizationCache(); if (cache != null) {
     * for (Object key : cache.keys()) { cache.remove(key); } } }
     */

    public String getDefaultRoles() {
        return defaultRoles;
    }

    public String getDefaultPurviews() {
        return defaultPurviews;
    }

    public void setDefaultRoles(String defaultRoles) {
        this.defaultRoles = defaultRoles;
    }

    public void setDefaultPurviews(String defaultPurviews) {
        this.defaultPurviews = defaultPurviews;
    }
}
